<template>
  <div style="width: 96%;margin:0 auto">
    <!-- 头部按钮 -->
    <div style="padding-top:12px">
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="dialogFormVisible = true"
      >新建</el-button>
      <el-button type="primary" icon="el-icon-refresh" @click="flushed">刷新</el-button>

      <!-- 搜索框输入表单 -->
      <el-form :inline="true" :model="searchData" class="search-form">
        <el-form-item>
          <el-input v-model="searchData.examName" placeholder="按考试名称查询" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchData.examTimeLimit" placeholder="按考试时长查询" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchData.examStartDate"
            type="date"
            placeholder="按考试开始日期查询"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleExamSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 考试列表表格展示 -->
    <el-table
      :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
      border
      :default-sort="{prop: 'date', order: 'descending'}"
      style="width: 100%;margin-top:7px;"
    >
      <!-- <el-table-column fixed prop="id" label="序号" width="50" align="center"></el-table-column> -->
      <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
      <el-table-column prop="examName" label="考试名称" width="240" align="center"></el-table-column>
      <el-table-column prop="examDescription" label="考试科目" width="120" align="center"></el-table-column>
      <el-table-column prop="examScore" label="总分数" align="center"></el-table-column>
      <el-table-column prop="examCreator" label="创建人" align="center"></el-table-column>
      <el-table-column prop="examTimeLimit" label="考试时长(分钟)" align="center"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" sortable width="252" align="center"></el-table-column>
      <el-table-column fixed="right" label="操作" width="252">
        <template slot-scope="scope">
          <el-button size="medium" type="success" plain @click="detail(scope.$index, scope.row)">详情</el-button>
          <el-button
            size="medium"
            type="primary"
            plain
            @click="edit(scope.row,scope.$index,tableData)"
          >编辑</el-button>
          <el-button size="medium" type="danger" plain @click="remove(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页展示考试列表 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length"
      >
        <!-- 总条数 -->
      </el-pagination>
    </div>

    <!-- 新建考试弹框 -->
    <el-dialog
      title="新建考试"
      :visible.sync="dialogFormVisible"
      height="auto"
      width="40%"
      align-center
    >
      <el-dialog width="30%" title="确认信息" :visible.sync="innerVisible" append-to-body>
        <span>是否在离开页面前保存考试信息？</span>
        <div slot="footer" class="dialog-footer">
          <el-button @click="revise">返回修改</el-button>
          <el-button @click="save">保存</el-button>
        </div>
      </el-dialog>
      <el-steps :active="active" finish-status="success" style="margin-bottom:20px" align-center>
        <el-step title="考试描述"></el-step>
        <el-step title="选择时间"></el-step>
        <el-step title="选择题目"></el-step>
      </el-steps>
      <div v-show="active == 0">
        <el-form
          :model="form"
          class="add-exam-form"
          :rules="addExamRules"
          label-width="100px"
          ref="firstForm"
        >
          <el-form-item label="创建人：" prop="creater">
            <el-input v-model="form.creater" placeholder="请输入创建人姓名"></el-input>
          </el-form-item>
          <el-form-item label="考试名称：" prop="name">
            <el-input v-model="form.name" placeholder="请输入考试名称"></el-input>
          </el-form-item>
          <el-form-item label="考试描述：" prop="desc">
            <el-input
              type="textarea"
              v-model="form.desc"
              :autosize="{ minRows: 2}"
              placeholder="请输入考试描述"
              maxlength="100"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="考试班级：" prop="class">
            <el-select v-model="form.class" placeholder="请选择">
              <el-option
                v-for="item in form.classOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="dialogFormVisible=false,active=0">取消</el-button>
            <el-button
              type="primary"
              style="margin-top: 12px;"
              @click="next('firstForm')"
            >{{createStep}}</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-show="active == 1">
        <el-form
          :model="form"
          class="add-exam-form"
          ref="secondForm"
          :rules="addExamRules"
          label-width="100px"
        >
          <el-form-item label="考试限时：" prop="examTime">
            <el-input-number
              type="number"
              style="width:150px;"
              v-model="form.examTime"
              controls-position="right"
              :min="60"
              :max="120"
            ></el-input-number>&nbsp;分钟
          </el-form-item>
          <el-form-item label="开始时间：" prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              clearable
              style="width: 100%"
              :picker-options="startDatePicker"
              type="datetime"
              :placeholder="'请选择考试开始时间'"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间：" prop="endTime">
            <el-date-picker
              v-model="form.endTime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              clearable
              style="width: 100%"
              :picker-options="endDatePicker"
              type="datetime"
              :placeholder="'请选择考试结束时间'"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button @click="last">上一步</el-button>
            <el-button
              type="primary"
              style="margin-top: 12px;"
              @click="next('secondForm')"
            >{{createStep}}</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-show="active == 2">
        <el-form :model="form" class="add-exam-form2" inline ref="thirdForm" :rules="addExamRules">
          <el-form-item label="选择题型：" size="small">
            <el-cascader
              v-model="form.qtype"
              :options="form.qtypeOptions"
              :props="{ expandTrigger: 'hover' }"
              @change="handleExamType"
              clearable
              placeholder="请选择题目类型"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="选择题目：" size="small" style="float:right">
            <el-select v-model="form.topic" multiple placeholder="请选择题目">
              <el-option
                v-for="item in form.topicOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-table border size="small" class="add-exam-table">
            <el-table-column label="题目" prop="title" />
            <el-table-column label="分值" prop="score" />
          </el-table>
          <el-form-item style="margin-left:25.5%">
            <el-button @click="last">上一步</el-button>
            <el-button
              type="primary"
              style="margin-top: 12px;"
              @click="next('thirdForm')"
            >{{createStep}}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <!-- 编辑考试弹框 -->
    <el-dialog title="编辑考试" :visible.sync="dialogFormEdit" height="auto" width="550px">
      <!-- 保存提示 -->
      <el-dialog width="400px" title="确认信息" :visible.sync="innerVisible" append-to-body>
        <span>是否在离开页面前保存考试信息？</span>
        <div slot="footer" class="dialog-footer">
          <el-button @click="innerVisible=false">返回修改</el-button>
          <el-button @click="editSave(index)">保存</el-button>
        </div>
      </el-dialog>
      <hr />
      <el-form :model="editDate" style="padding:20px;" :rules="addExamRules" label-width="95PX">
        <el-form-item label="考试名称：" prop="name">
          <el-input v-model="editDate.name" placeholder="请输入考试名称"></el-input>
        </el-form-item>
        <el-form-item label="考试科目：" prop="desc">
          <el-input
            type="textarea"
            v-model="editDate.desc"
            :autosize="{ minRows: 2}"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="考试限时：" prop="examTime">
          <el-input-number
            style="width:150px;"
            v-model="editDate.examTime"
            controls-position="right"
            :min="60"
          ></el-input-number>&nbsp;分钟
        </el-form-item>
        <el-form-item label="开始时间：" prop="startTime">
          <el-date-picker
            v-model="editDate.startTime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
            style="width: 100%"
            :picker-options="startDatePicker"
            type="datetime"
            :placeholder="'请选择考试开始时间'"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间：" prop="endTime">
          <el-date-picker
            v-model="editDate.endTime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
            style="width: 100%"
            :picker-options="endDatePicker"
            type="datetime"
            :placeholder="'请选择考试结束时间'"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <hr />

      <div slot="footer" class="dialog-footer">
        <el-button @click="innerVisible=true">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import moment, { months } from "moment";
import allApis from "@/request";
const { fetchExamList,fetchClassAll } = allApis;
export default {
  name: "ExamManagement",
  data() {
    return {
      tableData1: [],
      tableData: [
        {
          id: "1",
          cover: "LAUNCH",
          name: "Java基础",
          score: "100",
          creater: "张三",
          duration: "90",
          updateTime: "2022-09-03",
          desc: "国庆节作业",
          startTime: "2022-10-01 12:00",
          endTime: "2022-10-07 13:00"
        },
        {
          id: "2",
          cover: "LAUNCH",
          name: "HTML+CSS",
          score: "100",
          creater: "李四",
          duration: "90",
          updateTime: "2022-09-04",
          desc: "国庆节作业",
          startTime: "2022-10-01 12:00",
          endTime: "2022-10-07 13:00"
        },
        {
          id: "3",
          cover: "LAUNCH",
          name: "JS基础",
          score: "100",
          creater: "王五",
          duration: "90",
          updateTime: "2022-09-07",
          desc: "国庆节作业",
          startTime: "2022-10-01 12:00",
          endTime: "2022-10-07 13:00"
        },
        {
          id: "4",
          cover: "LAUNCH",
          name: "Jquery",
          score: "100",
          creater: "邵六",
          duration: "120",
          updateTime: "2022-09-05",
          desc: "国庆节作业",
          startTime: "2022-10-01 12:00",
          endTime: "2022-10-07 13:00"
        },
        {
          id: "5",
          cover: "LAUNCH",
          name: "VUE",
          score: "100",
          creater: "马七",
          duration: "90",
          updateTime: "2022-10-03",
          desc: "国庆节作业",
          startTime: "2022-10-01 12:00",
          endTime: "2022-10-07 13:00"
        },
        {
          id: "6",
          cover: "LAUNCH",
          name: "数据基础",
          score: "100",
          creater: "赵八",
          duration: "180",
          updateTime: "2022-10-01",
          desc: "国庆节作业",
          startTime: "2022-10-01 12:00",
          endTime: "2022-10-07 13:00"
        },
        {
          id: "7",
          cover: "LAUNCH",
          name: "后端基础",
          score: "100",
          creater: "周九",
          duration: "120",
          updateTime: "2022-09-15",
          desc: "国庆节作业",
          startTime: "2022-10-01 12:00",
          endTime: "2022-10-07 13:00"
        }
      ],
      dialogFormVisible: false,
      dialogFormEdit: false,
      innerVisible: false,
      searchDialogVisible: false,

      active: 0,
      createStep: "下一步",
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页的数据条数
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate(),

      // 编辑表单
      editDate: {
        name: "",
        examTime: "",
        desc: "",
        startTime: "",
        endTime: ""
      },

      // 搜索表单
      searchData: {
        examName: "",
        eaxamTimeLimit: "",
        examStartDate: ""
      },
      options: [],

      // 新建考试表单
      form: {
        creater: "",
        name: "",
        desc: "",
        resource: "",
        examTime: 90,
        startTime: "",
        endTime: "",
        class: "",
        index: "",
        qtype: "",
        qtypeOptions: [
          {
            value: "radio",
            label: "单选",
            children: [
              {
                value: "simple",
                label: "简单"
              },
              {
                value: "easy",
                label: "容易"
              },
              {
                value: "difficulty",
                label: "困难"
              }
            ]
          },
          {
            value: "selection",
            label: "多选",
            children: [
              {
                value: "simple",
                label: "简单"
              },
              {
                value: "easy",
                label: "容易"
              },
              {
                value: "difficulty",
                label: "困难"
              }
            ]
          },
          {
            value: "judgment",
            label: "判断",
            children: [
              {
                value: "simple",
                label: "简单"
              },
              {
                value: "easy",
                label: "容易"
              },
              {
                value: "difficulty",
                label: "困难"
              }
            ]
          }
        ],
        classOptions: [
          {
            value: "选项1",
            label: "JAVA基础"
          },
          {
            value: "选项2",
            label: "前端"
          },
          {
            value: "选项3",
            label: "后端"
          },
          {
            value: "选项4",
            label: "数据"
          }
        ],
        topic: [],
        topicOptions: [
          {
            value: "选项1",
            label: "黄金糕"
          },
          {
            value: "选项2",
            label: "双皮奶"
          },
          {
            value: "选项3",
            label: "蚵仔煎"
          },
          {
            value: "选项4",
            label: "龙须面"
          },
          {
            value: "选项5",
            label: "北京烤鸭"
          }
        ]
      },

      // 表单验证
      addExamRules: {
        creater: [
          { required: true, message: "请输入创建人姓名", trigger: "blur" }
        ],
        name: [{ required: true, message: "请输入考试名称", trigger: "blur" }],
        desc: [{ required: true, message: "请输入描述信息", trigger: "blur" }],
        class: [{ required: true, message: "请选择班级", trigger: "change" }],
        examTime: [
          { required: true, message: "请选择时间限制", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "请选择开始时间", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "请选择结束时间", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    // 跳转详情
    async detail(index, row) {
      // 点击详情按钮，跳转到详情页面
      this.$router.push({ name: "detail" });
      // this.$router.push({name:"details",query:{res:res}});
      const { data: res } = await request.post("", { id: row.id });
    },

    // 分页功能
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.currentPage = 1;
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
    },

    //刷新
    flushed() {
      // this.$router.go(0);
      this.getTableData();
      //this.loading = true;
      /* this.$router.push({
        name: "exammanagement"
      }); */
    },

    /** 获取数据 */
    getTableData() {
      // const res = fetchExamList();
      // console.log(res);
      fetchExamList().then(res => {
        console.log(res);
        if (res.data.code === 200) {
          this.tableData = res.data.data;
        }
      });
    },

    // 模糊查询
    handleExamSearch() {
      fetchExamList(this.searchData).then(res => {
        console.log(res);
        if (res.data.code === 200) {
          this.tableData = res.data.data;
        }
      });
      // const form = this.searchData;
      // const { name, time, updateTime } = form;
      // console.log(time);
      // let update = Date.parse(moment(updateTime).format("YYYY-MM-DD"));
      // if (name === "" && time === "" && updateTime === "") {
      //   this.getTableData();
      //   // console.log(form);
      //   // this.$message.warning("请输入查询项");
      // } else {
      //   const res = this.tableData.filter(item => {
      //     // console.log(Date.parse(item.updateTime));
      //     return (
      //       item.duration == time ||
      //       item.name == name ||
      //       Date.parse(item.updateTime) == update
      //     );
      //   });
      //   console.log(res);
      //   this.$nextTick(() => {
      //     // dom元素更新后执行，因此这里能正确打印更改之后的值
      //     this.tableData = res; // 改变了的值
      //   });
      // }
      // 将查询到的数据替换表格数据，重新渲染页面
    },

    //选题功能
    handleExamType(value) {
      console.log(value);
    },

    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    // 下一步
    next(formName) {
      console.log(formName);
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.active++;
          if (this.active == 2) {
            this.createStep = "提交";
          }
          if (this.active == 3) {
            this.innerVisible = true;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    last() {
      if (this.active > 0) {
        this.active--, (this.createStep = "下一步");
      }
      if (this.active == 2) {
        this.createStep = "提交";
      }
    },
    revise() {
      this.active = 2;
      this.innerVisible = false;
    },

    // 保存功能
    save() {
      this.innerVisible = false;
      this.dialogFormVisible = false;
      this.active = 0;
      this.createStep = "下一步";
    },

    // 编辑功能保存按钮
    editSave(index) {
      this.innerVisible = false;
      this.dialogFormEdit = false;
      this.tableData[index].name = this.editDate.name;
      this.tableData[index].duration = this.editDate.examTime;
      this.tableData[index].desc = this.editDate.desc;
      this.tableData[index].startTime = this.editDate.startTime;
      this.tableData[index].endTime = this.editDate.endTime;
    },

    // 编辑功能
    edit(row,index, tableData) {
      // console.log(index);
      this.dialogFormEdit = true;
      this.index = index;
      this.editDate = JSON.parse(JSON.stringify(this.editDate)); //先JSON.stringfy再JSON.parse
      this.editDate.name = tableData[index].examName;
      this.editDate.examTime = tableData[index].examTimeLimit;
      this.editDate.desc = tableData[index].examDescription;
      this.editDate.startTime = tableData[index].examStartDate;
      this.editDate.endTime = tableData[index].endTime;
    },

    // 删除功能
    remove(index) {
      this.tableData.splice(index, 1);
    },
    //删除考试接口
    remove() {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    //时间选择验证方式
    beginDate() {
      //开始时间选择验证方式
      const self = this;
      return {
        disabledDate(time) {
          if (self.form.endTime) {
            //如果结束时间不为空，则小于结束时间
            return new Date(self.form.endTime).getTime() < time.getTime();
          } else {
            return time.getTime() < Date.now(); //结束时间为空，开始时间大于等于当前值
          }
        }
      };
    },
    processDate() {
      //结束时间选择验证方式
      const self = this;
      return {
        disabledDate(time) {
          if (self.form.startTime) {
            //如果开始时间不为空，则结束时间大于开始时间
            return new Date(self.form.startTime).getTime() > time.getTime();
          } else {
            return time.getTime() < Date.now(); //开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    }
  },

  beforeMount() {
    this.getTableData();
  }
};
</script>

<style lang="scss" scoped>
.add-exam-form {
  margin-top: 40px;
  margin-left: 10%;
  width: 77%;
}
.add-exam-form2 {
  margin-top: 30px;
  // margin-left: 12%;
  ::v-deep .add-exam-table {
    margin-top: 10px;
    width: 100%;
  }
}
.block {
  text-align: center;
  margin-top: 1%;
}
.search-form {
  margin: 0;
  display: inline;
  float: right;
}
</style> 